import React, { Component } from 'react';
import { toJS } from 'mobx';
import { observer, inject } from 'mobx-react';
import { withRouter } from 'react-router-dom';
import classnames from 'classnames';
import { Tools, InputInterval, Bubble, Radio, Toast } from 'weaver-mobile';
import './index.less';

import {
  SelectPage,
  Browser,
  BrowserHrm,
  RouteLayout
 } from 'weaver-mobile-page'

const ButtonGroup = RouteLayout.ButtonGroup;
const RadioItem = Radio.RadioItem;
const getLabel = Tools.getLabel;

function noop() { }
const options = () => [
  {
    key: '3',
    showname: getLabel(27511, '部门'),
  },
  {
    key: '2',
    showname: getLabel(523258, '分部'),
  },
  {
    key: '5',
    showname: getLabel(523273, '所有人'),
  },
  {
    key: '1',
    showname: getLabel(502300, '人力资源'),
  },
  {
    key: '4',
    showname: getLabel('122', '角色'),
  },
  {
    key: '6',
    showname: getLabel('509248', '岗位'),
  },
  {
    key: '7',
    showname: getLabel('24002', '群组')
  }
];
const optionsType = () => [
  {
    key: '0',
    showname: getLabel(27511, '部门'),
  },
  {
    key: '1',
    showname: getLabel(523258, '分部'),
  },
  {
    key: '2',
    showname: getLabel(505977, '总部'),
  },
];
// 对应valueArray
const optionsJob = () => [
  {
    key: '2',
    showname: getLabel('505977', '总部'),
  },
  {
    key: '1',
    showname: getLabel('505980', '指定分部'),
  },
  {
    key: '0',
    showname: getLabel('505981', '指定部门'),
  },
];


@inject('powerStore')
@withRouter
@observer
export default class BrowserHrmConditionNormal extends Component {
  static displayName = 'BrowserHrmConditionNormal';
  static defaultProps = {
    prefixCls: 'wm-browser-hrm-condition-normal',
    getContainer: noop,
  }

  constructor() {
    super();

    this.state = {
      rightType: '1',
      rightTypespan: getLabel('33564', '查看'),
      chatGroup: [],
      chatGroupspan: [],
      browserValue7: []
    }
  }

  componentDidMount() {
    const { store: { setState } } = this.props;
    setState({
      valueArrayType: ['3'],
      // valueArrayLevel: ['2'],
      replaceDataItem: {},
      browserValue: [],
      browserValue3: [],
      browserValue2: [],
      browserValue4: [],
      browserValue6: [],
      browserHrmValue: [],
      seclevel: [0, 100],
    });
    if ('isShowSecLevel' in this.props) {
      setState({ isShowSecLevel: this.props.isShowSecLevel });
    }
  }

  onTypeChange = (datas) => {
    const { store: { setState } } = this.props;
    setState({ seclevel: [0, 100] });
    const arr = [];
    datas.map((v) => {
      arr.push(v.key);
    });
    let obj = {
      sharetypespan: datas[0] ? datas[0].showname : '',
      sharetype: datas[0] ? datas[0].key : '',
    };
    if (arr[0] === '4') {
      obj = {
        sharetypespan: datas[0] ? datas[0].showname : '',
        sharetype: datas[0] ? datas[0].key : '',
        rolelevelspan: getLabel(27511, '部门'),
        rolelevel: '0',
      };
      setState({ valueArrayLevel: ['0'] });
    }
    if (arr[0] === '6') {
      obj = {
        sharetypespan: datas[0] ? datas[0].showname : '',
        sharetype: datas[0] ? datas[0].key : '',
        joblevelspan: getLabel(140, '总部'),
        joblevel: '2',
        jobfield: '-1',
      };
      setState({ valueArrayLevel: ['2'] });
    }
    if (arr[0] === '5') {
      obj = Object.assign({}, obj, { relatedshare: '-1' });
    }
    setState({
      valueArrayType: arr,
      replaceDataItem: Object.assign({}, obj),
      browserValue3: [],
      browserValue2: [],
      browserValue4: [],
      browserValue6: [],
      browserHrmValue: [],
      seclevel: [0, 100],
    });

    this.setState({ 
      chatGroup: [],
      chatGroupspan: [],
      browserValue7: []
    });
  }

  onLevalChange = (datas) => {
    const { store: { setState, replaceDataItem, valueArrayType } } = this.props;
    const arr = [];
    datas.map((v) => {
      arr.push(v.key);
    });
    let obj = {};
    if (valueArrayType[0] === '4') {
      obj = {
        rolelevelspan: datas[0] ? datas[0].showname : '',
        rolelevel: datas[0] ? datas[0].key : '',
      };
    } else {
      obj = {
        joblevelspan: datas[0] ? datas[0].showname : '',
        joblevel: datas[0] ? datas[0].key : '',
      };
    }
    setState({ valueArrayLevel: arr, replaceDataItem: Object.assign({}, replaceDataItem, obj) });
  }

  handleBrowserChange = (...arg) => {
    const { store, store: { replaceDataItem, valueArrayType, setState } } = this.props;
    let obj;
    let valueArray;
    if (arg[2].length > 0) {
      obj = {
        relatedsharespan: arg[2][0].name || arg[2][0].lastname,
        relatedshare: arg[2][0].id,
      };
      if (valueArrayType[0] === '1') {
        valueArray = [];
        arg[2].map((item) => {
          if (item.users) {
            item.users.map((items) => {
              valueArray.push({ id: items.id, name: items.lastname });
            });
          } else {
            valueArray.push({ id: item.id, name: item.name || item.lastname });
          }
        });
      } else {
        valueArray = arg[2];
      }
    }
    setState({ replaceDataItem: Object.assign({}, replaceDataItem, obj), browserValue: arg[2] });
    store.setBrowserValue(valueArrayType[0], valueArray);
  }

  onChartGroupChange = (ids, names, datas) => {
    this.setState({
      chatGroup: ids,
      chatGroupspan: names,
      browserValue7: datas
    });
  }

  handleLevalChange = (...arg) => {
    const { store, store: { replaceDataItem, valueArrayLevel, valueArrayType, setState } } = this.props;
    let obj = {};
    if ((valueArrayType[0] === '3' || valueArrayType[0] === '2') && arg[2].length > 0) { // 分部 部门
      obj = {
        relatedsharespan: arg[2][0].name,
        relatedshare: arg[2][0].id,
      };
      store.setBrowserValue(valueArrayType[0], arg[2]);
      setState({ replaceDataItem: Object.assign({}, replaceDataItem, obj), browserValue: arg[2] });
    } else if (arg[2].length > 0) { // 岗位
      if (arg[2] && arg[2][0].joblevel !== '2') {
        let jobfieldspan = '';
        let jobfield = '';
        arg[2].map((item, index) => {
          jobfieldspan += index === arg[2].length - 1 ? `${item.name}` : `${item.name},`;
          jobfield += index === arg[2].length - 1 ? `${item.id}` : `${item.id},`;
        });
        // jobfield = arg[2][0].id.substring(0, 1);
        obj = {
          jobfieldspan,
          jobfield,
        };
      }
      switch (valueArrayLevel[0]) {
        case '0':
          setState({ browserValue3: arg[2] });
          break;
        case '1':
          setState({ browserValue2: arg[2] });
          break;
        default:
          break;
      }
      setState({ replaceDataItem: Object.assign({}, replaceDataItem, obj) });
    }
  }

  handleInterval = (value) => {
    const { replaceDataItem, setState } = this.props.store;
    const obj = {
      seclevel: `${value[0]}-${value[1]}`,
    };
    setState({ seclevel: value, replaceDataItem: Object.assign({}, replaceDataItem, obj) });
  }

  handleRightType = (rightType, rightTypespan) => {
    this.setState({ rightType, rightTypespan });
  }

  doValidate = (newItem) => {
    const validate = { message: '', pass: true };
    // 校验���否输入安全级别
    if (newItem.sharetype !== '1' && newItem.sharetype !== '6') {
      if (!newItem.seclevel) {
        newItem.seclevel = '0-100';
      }
      const secArray = newItem.seclevel.split('-');
      // 校验安全是否完整
      secArray.map((item) => {
        if (!item) {
          validate.message = getLabel(683, '安全级别');
          validate.pass = false;
        }
      });
    }
    // 校验岗位 指定部门分部
    if (newItem.sharetype === '6' && newItem.joblevel !== '2' && !newItem.jobfieldspan) {
      validate.message = newItem.joblevelspan;
      validate.pass = false;
    }
    // 校验条件内容是否有值 包含岗位条件内容
    if (newItem.sharetype === '7') {
      const { chatGroup } = this.state;
      
      if (!chatGroup.length) {
        validate.message = getLabel(523650, '条件内容');
        validate.pass = false;
      }
    }else if (newItem.sharetype !== '5' && !newItem.relatedshare) {
      validate.message = getLabel(523650, '条件内容');
      validate.pass = false;
    }
    return validate;
  }
  getids = (valueArray) => {
    const jobfield = [];
    valueArray.map((item) => {
      if (item.sharetype === '6') {
        jobfield.push(item.jobfield);
      } else {
        jobfield.push(item.relatedshare);
      }
    });
    return jobfield.join();
  }
  getValueSpan = (valueArray) => {
    const { store: { isShowSecLevel, getValueSpan } } = this.props;
    const array = [];
    valueArray.map((item) => {
      const str = getValueSpan(item, isShowSecLevel);
      array.push(str);
    });
    return array;
  }
  // 给每条数据生成随机id，用于删除
  getID = () => Number(Math.random().toString().substr(3, 4) + Date.now()).toString(36);

  canCelClick = () => {
    const { powerStore, history } = this.props;

    history.go(-1);
    powerStore.canCelClick();
  }

  btnClick = () => {
    const { onChange, store: { replaceDataItem, valueArrayType, valueArray, list, setState, browserValue }, history, powerStore } = this.props;
    let newItem;
    // const id = valueArray.length > 0 ? valueArray[valueArray.length - 1].id + 1 : 0;
    const numid = this.getID();
    const newArray = [];
    if (!replaceDataItem.sharetype) {
      // 没有切换类型时，将类型默认设置为部门
      newItem = Object.assign({}, replaceDataItem,
        {
          id: numid,
          sharetype: '3',
          sharetypespan: getLabel(388109, '部门'),
        });
    } else {
      newItem = Object.assign({}, replaceDataItem, { id: numid });
    }
    const isValidate = this.doValidate(newItem);
    if (isValidate.pass) {
      browserValue.map((item) => {
        if (valueArrayType[0] === '1' && item.users) {
          item.users.map((items) => {
            newItem = Object.assign({}, newItem, { id: numid, relatedsharespan: items.lastname, relatedshare: items.id });
            // numid += 1;
            newArray.push(newItem);
          });
        } else {
          newItem = Object.assign({}, newItem, { id: numid, relatedsharespan: item.name || item.lastname, relatedshare: item.id });
          // numid += 1;
          newArray.push(newItem);
        }
      });
      if (browserValue.length === 0) {
        newArray.push(newItem);
      }
      const newValueArray = valueArray.concat(newArray);
      setState({
        valueArray: newValueArray,
      });
      list.setState({ data: newValueArray });
      if (typeof onChange === 'function') {
        onChange(this.getids(newValueArray), this.getValueSpan(newValueArray), newValueArray);
      }
      
      if (newArray.length > 1) { // 岗位
        const relatedshare = [];
        const relatedsharespan = [];

        newArray.forEach(arr => {
          relatedshare.push(arr.relatedshare);
          relatedsharespan.push(arr.relatedsharespan);
        });

        newArray[0].relatedshare = relatedshare.join(',');
        newArray[0].relatedsharespan = relatedsharespan.join(',');
      }

      if (newArray[0].joblevel === '2') {
        newArray[0].joblevel = '1';
      } else if (newArray[0].joblevel === '1') {
        newArray[0].joblevel = '2';
      } else if (newArray[0].joblevel === '0') {
        newArray[0].joblevel = '3';
      }

      const { rightType, rightTypespan, chatGroup, chatGroupspan } = this.state;

      powerStore.addShare({ ...newArray[0], rightType, rightTypespan, chatGroup, chatGroupspan }).then(() => {
        Toast.success(getLabel(506024, '添加成功'), 1);

        setTimeout(() => {
          history.go(-1);
        }, 1000);
      });
    } else {
      Bubble.error(`${isValidate.message}${getLabel(18622, '不能为空')}`, 1);
    }
  }

  render() {
    const {
      className,
      prefixCls,
      getContainer = () => {},
      style,
      store: {
        id, selectPage, selectPage2, valueArrayType, replaceDataItem, seclevel,
        valueArrayLevel, browser3, browser2, browser6, browser4, browser7, browserHrm,
        browserValue3, browserValue2, browserValue6, browserValue4, browserHrmValue,
      },
      isSingle = false,
      appDetachDisableAll,
    } = this.props;
    const { browserValue7 } = this.state;
    const wrapCls = classnames(prefixCls, className, 'wm-route-layout');
    const selectPageOptions = appDetachDisableAll ? options().filter(o => o.key !== '5') : options();
    return (
      <RouteLayout getContainer={getContainer}>
        {/* <QueueAnim> */}
        <div
          key={id}
          className={wrapCls}
          style={style}
        >
          <SelectPage
            options={selectPageOptions}
            store={selectPage}
            label={getLabel(523649, '类型')}
            viewAttr={3}
            valueArray={valueArrayType}
            onChange={datas => this.onTypeChange(datas)}
          />
          {
            valueArrayType[0] === '1' &&
            <BrowserHrm
              label={getLabel(523650, '条件内容')}
              type={1}
              isSingle={isSingle}
              store={browserHrm}
              viewAttr={3}
              onChange={this.handleBrowserChange}
              valueArray={browserHrmValue}
            />
          }
          {
            valueArrayType[0] === '4' &&
            <Browser
              label={getLabel(523650, '条件内容')}
              type={65}
              isSingle={isSingle}
              store={browser4}
              viewAttr={3}
              onChange={this.handleBrowserChange}
              valueArray={browserValue4}
            />
          }
          {
            valueArrayType[0] === '6' && <Browser
              label={getLabel(523650, '条件内容')}
              type={24}
              isSingle={isSingle}
              store={browser6}
              viewAttr={3}
              onChange={this.handleBrowserChange}
              valueArray={browserValue6}
            />
          }
          {(valueArrayType[0] === '4' || valueArrayType[0] === '6') && <SelectPage
            options={valueArrayType[0] === '6' ? optionsJob() : optionsType()}
            store={selectPage2}
            label={valueArrayType[0] === '6' ? getLabel(28169, '岗位级别') : getLabel(139, '级别')}
            viewAttr={3}
            valueArray={valueArrayLevel}
            onChange={datas => this.onLevalChange(datas)}
          />}
          {
            (valueArrayType[0] === '3' ||
              (valueArrayType[0] === '6' && replaceDataItem.joblevelspan === getLabel(19438, '指定部门')))
            &&
            <Browser
              label={replaceDataItem.joblevelspan === getLabel(19438, '指定部门') ?
                replaceDataItem.joblevelspan : getLabel(523650, '条件内容')}
              type={4}
              isSingle={isSingle}
              store={browser3}
              viewAttr={3}
              onChange={this.handleLevalChange}
              valueArray={browserValue3}
            />
          }
          {
            (valueArrayType[0] === '2' ||
              (valueArrayType[0] === '6' && replaceDataItem.joblevelspan === getLabel(19437, '指定分部')))
            &&
            <Browser
              label={replaceDataItem.joblevelspan === getLabel(19437, '指定分部') ?
                replaceDataItem.joblevelspan : getLabel(523650, '条件内容')}
              type={164}
            isSingle={isSingle}
              store={browser2}
              viewAttr={3}
              onChange={this.handleLevalChange}
              valueArray={browserValue2}
               />
          }
         {(valueArrayType[0] === '4' ||
            valueArrayType[0] === '2' ||
            valueArrayType[0] === '3' ||
            valueArrayType[0] === '5') && <InputInterval
              min={[0, 100]}
              max={[0, 100]}
              value={toJS(seclevel)}
              required
              label={getLabel(683, '安全级别')}
              onChange={this.handleInterval}
            />}
            {
              valueArrayType[0] === '7' &&
              <Browser
              label={getLabel(523650, '条件内容')}
                type={'EMChatGroup'}
                isSingle={isSingle}
                store={browser7}
                viewAttr={3}
                valueArray={browserValue7}
                onChange={(ids, names, datas) => this.onChartGroupChange(ids, names, datas)}
              />
            }
            {
              <div className='wea-edc-mobile-power'>
                <RadioItem
                  checked={this.state.rightType === '1' } 
                  onChange={() => this.handleRightType('1', '查看')}
                > {getLabel(33564, '查看')} 
                </RadioItem>
                <RadioItem
                  checked={this.state.rightType === '2' } 
                  onChange={() => this.handleRightType('2', '维护')}
                > 
                  {getLabel(513430, '维护')} 
                </RadioItem>
              </div>
            }
          <ButtonGroup
            data={[
              { key: 'cancel',
                text: getLabel(31129, '取消'),
                onClick: this.canCelClick,
                type: 'ghost'
              },{
                key: 'submit',
                text: `${getLabel(83446, '确定')}`,
                onClick: this.btnClick,
                type: 'primary',
              }]}
          />
        </div>
      </RouteLayout>
    );
  }
}
